<template>
  <div class="menu-management">
    <h2 class="title">菜单管理</h2>
    <div class="toolbar">
      <el-select v-model="cuisineType" placeholder="选择菜系类型" @change="handleCuisineChange" style="width: 200px;">
        <el-option label="荤菜" value="荤菜"></el-option>
        <el-option label="素菜" value="素菜"></el-option>
        <el-option label="汤类" value="汤类"></el-option>
        <el-option label="主食类" value="主食类"></el-option>
      </el-select>
      <el-button type="danger" @click="addToCart" style="margin-left: 20px;">加入购物车</el-button>
      <el-button type="primary" @click="showCart" style="margin-left: 20px;">购物车列表</el-button>
      <el-button type="info" @click="showOrderDetails" style="margin-left: 20px;">订单详情列表</el-button>
    </div>
    <div class="menu-list">
      <div class="menu-item" v-for="item in pagedGridResult.rows" :key="item.id">
        <el-checkbox v-model="selectedItems" :label="item.id" class="hidden-checkbox"></el-checkbox>
        <img :src="item.imageUrl" alt="菜品图片" @error="handleImageError(item)" />
        <div class="item-name">{{ item.dishDescription }}</div>
      </div>
    </div>
    <div class="pagination">
      <span>第 {{ page }} 页 / 共 {{ pagedGridResult.total }} 页</span>
      <el-button @click="prevPage" :disabled="page === 1">上一页</el-button>
      <el-button @click="nextPage" :disabled="page === pagedGridResult.total">下一页</el-button>
    </div>
    <el-dialog :visible.sync="cartDialogVisible" title="购物车列表" width="60%">
      <el-table ref="cartTable" :data="cartItems" @selection-change="handleCartSelectionChange" border stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="menuId" label="菜品名称"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="imageUrl" label="图片">
          <template slot-scope="scope">
            <img :src="menuDetails[scope.row.menuId]?.imageUrl" alt="菜品图片" class="cart-item-image" @error="handleImageError(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="placeOrder">下单</el-button>
        <el-button @click="cartDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="orderDialogVisible" title="订单详情列表" width="60%">
      <el-table :data="orderDetails" border stripe>
        <el-table-column prop="id" label="订单ID"></el-table-column>
        <el-table-column prop="createdById" label="创建者">
          <template slot-scope="scope">
            {{ mapUserId(scope.row.createdById) }}
          </template>
        </el-table-column>
        <el-table-column prop="receivedById" label="接收者">
          <template slot-scope="scope">
            {{ mapUserId(scope.row.receivedById) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderRemark" label="订单备注"></el-table-column>
        <el-table-column prop="orderDetails" label="订单详情">
          <template slot-scope="scope">
            <el-table :data="scope.row.orderDetails" border stripe>
              <el-table-column prop="menuId" label="菜品名称">
                <template slot-scope="subScope">
                  {{ getDishName(subScope.row.menuId) }}
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'MenuManagement',
  data() {
    return {
      page: 1,
      limit: 10,
      cuisineType: '荤菜', // 默认值设置为荤菜
      pagedGridResult: {
        page: 1,
        total: 0,
        records: 0,
        rows: []
      },
      selectedItems: [],
      cartDialogVisible: false,
      orderDialogVisible: false,
      cartItems: [],
      orderDetails: [],
      selectedCartIds: [], // 新增，用于存储选中的购物车项ID
      menuDetails: {} // 新增，用于存储菜单详细信息
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      axios.get('/menu/page', {
        params: {
          page: this.page,
          limit: this.limit,
          cuisineType: this.cuisineType
        }
      })
          .then(response => {
            if (response.data.code === 200) {
              this.pagedGridResult = response.data.data;
            } else {
              console.error('Error fetching data:', response.data.msg);
            }
          })
          .catch(error => {
            console.error('Error fetching data:', error);
          });
    },
    prevPage() {
      if (this.page > 1) {
        this.page--;
        this.fetchData();
      }
    },
    nextPage() {
      if (this.page < this.pagedGridResult.total) {
        this.page++;
        this.fetchData();
      }
    },
    addToCart() {
      if (this.selectedItems.length === 0) {
        this.$message({
          message: '还没有选择具体菜品',
          type: 'warning'
        });
        return; // 提前返回，防止继续执行后续代码
      }

      const cards = this.selectedItems.map(itemId => {
        const item = this.pagedGridResult.rows.find(row => row.id === itemId);
        return `${item.id}`;
      }).join(',');

      axios.get('/cart/batchAdd', {
        params: {
          cards: cards,
          userId: this.getUserId() // 假设有一个方法获取当前用户ID
        }
      })
          .then(response => {
            if (response.data.data === 0) {
              this.$message.success('加入购物车成功');
              this.updateCartItems(this.selectedItems);
            } else if (response.data.data === -1) {
              this.$message.error('购物车已经有10条数据，无法继续添加');
            } else {
              console.log('cards', cards);
              this.arrayResult = cards.split(',');
              this.$message.error("最多可以再添加" + (response.data.data) + "条数据");
            }
          })
          .catch(error => {
            console.error('Error adding to cart:', error);
            this.$message.error('加入购物车失败');
          });

      this.selectedItems = [];
    },
    updateCartItems(selectedItems) {
      selectedItems.forEach(itemId => {
        const item = this.pagedGridResult.rows.find(row => row.id === itemId);
        if (item) {
          const existingItem = this.cartItems.find(cartItem => cartItem.id === itemId);
          if (existingItem) {
            existingItem.quantity += 1;
          } else {
            this.cartItems.push({ ...item, quantity: 1 });
          }
        }
      });
    },
    fetchCartItems() {
      axios.get('/cart/list', {
        params: {
          userId: this.getUserId() // 假设有一个方法获取当前用户ID
        }
      })
          .then(response => {
            console.log('Response data:', response.data);
            if (response.data.code === 200) {
              this.cartItems = response.data.data.rows;
              this.cartDialogVisible = true; // 显示购物车对话框
              this.fetchMenuDetails(); // 自动获取菜单详细信息
            } else {
              this.$message.error('获取购物车列表失败: ' + response.data.message);
            }
          })
          .catch(error => {
            console.error('Error fetching cart items:', error);
            this.$message.error('获取购物车列表失败');
          });
    },
    fetchOrderDetails() {
      axios.get('/orders/orderDetails')
          .then(response => {
            console.log('Response data:', response.data);
            if (response.data.code === 200) {
              this.orderDetails = response.data.data;
              this.orderDialogVisible = true; // 显示订单详情对话框
            } else {
              this.$message.error('获取订单详情失败: ' + response.data.message);
            }
          })
          .catch(error => {
            console.error('Error fetching order details:', error);
            this.$message.error('获取订单详情失败');
          });
    },
    showCart() {
      this.fetchCartItems();
    },
    showOrderDetails() {
      this.fetchOrderDetails();
    },
    getUserId() {
      return localStorage.getItem('userId'); // 或者其他方法获取当前用户ID
    },
    handleCuisineChange() {
      this.page = 1;
      this.fetchData();
    },
    formatDate(date) {
      const d = new Date(date);
      return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
    },
    mapUserId(userId) {
      if (userId === 'jy') return '小金宝';
      if (userId === 'yjw') return '于妹妹';
      return userId;
    },
    getDishName(menuId) {
      return this.menuDetails[menuId]?.dishDescription || menuId;
    },
    handleCartSelectionChange(selectedItems) {
      this.selectedCartIds = selectedItems.map(item => item.id);
    },
    placeOrder() {
      if (this.selectedCartIds.length === 0) {
        this.$message({
          message: '还没有选择具体菜品进行下单',
          type: 'warning'
        });
        return; // 提前返回，防止继续执行后续代码
      }

      // 获取选中菜品的详细信息
      const selectedItemsDetails = this.cartItems.filter(item => this.selectedCartIds.includes(item.id));

      // 将选中菜品的详细信息转换为 JSON 字符串，并通过 query 参数传递
      this.$router.push({
        path: '/order-confirmation',
        query: {
          selectedItems: JSON.stringify(selectedItemsDetails)
        }
      });
    },
    fetchMenuDetails() {
      const menuIds = this.cartItems.map(item => item.menuId).join(',');
      axios.get('/menu/batchGet', {
        params: {
          ids: menuIds
        }
      })
          .then(response => {
            if (response.data) {
              response.data.forEach(menu => {
                this.$set(this.menuDetails, menu.id, menu);
              });
            } else {
              this.$message.error('获取菜单详情失败');
            }
          })
          .catch(error => {
            console.error('Error fetching menu details:', error);
            this.$message.error('获取菜单详情失败');
          });
    },
    handleImageError(row) {
      console.error('Image load error:', row.imageUrl);
    },
  }
};
</script>

<style scoped>
.menu-management {
  height: 100vh;
  background-image: url('../assets/pdx.png'); /* 确保路径正确 */
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start; /* 改为左对齐 */
  padding: 20px;
}

.title {
  color: black;
  margin-top: 20px;
  width: 100%; /* 添加 */
  text-align: center; /* 添加 */
}

.toolbar {
  width: 100%;
  display: flex;
  justify-content: flex-start; /* 将查询框放到最左边 */
  align-items: center; /* 使购物车按钮与下拉框对齐 */
  margin-bottom: 20px;
}

.menu-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* 改为左对齐 */
}

.menu-item {
  background: white;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin: 10px;
  padding: 10px;
  text-align: center;
  width: 260px; /* 增加宽度 */
  display: flex;
  flex-direction: column;
  align-items: center; /* 添加 */
}

.menu-item .el-checkbox {
  align-self: flex-start; /* 添加 */
  margin-bottom: 10px; /* 添加一些间距 */
}

.menu-item .hidden-checkbox .el-checkbox__label {
  display: none; /* 隐藏复选框标签 */
}

.menu-item img {
  border-radius: 5px;
  height: 220px; /* 增加高度 */
  object-fit: cover;
  width: 100%;
}

.item-name {
  font-weight: bold;
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: flex-end; /* 改为右对齐 */
  align-items: center;
}

.pagination span {
  margin-right: 10px;
}

/* 添加购物车对话框的样式 */
.shopping-cart {
  padding: 20px;
}

.cart-item-image {
  width: 80px;
  height: 80px;
  border-radius: 5px;
  object-fit: cover;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
}
</style>
